package team.epos.utils.servlet;

import org.apache.commons.lang3.StringUtils;
import team.epos.utils.annotation.RequestMethod;
import team.epos.utils.util.FileUploadUtil;
import team.epos.utils.util.ResourcesUtil;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Create by Vic Xu on 2018/7/12
 */
public class BaseServlet extends HttpServlet {

    private static final long serialVersionUID = -1039532634712700555L;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        dispatcher(req, resp);
    }

    private void dispatcher(HttpServletRequest req, HttpServletResponse resp) {
        String method = req.getParameter("method");
        String contentType = req.getContentType();
        if (StringUtils.isNotBlank(contentType) && contentType.contains("multipart/form-data")) {
            String imgPath = ResourcesUtil.resourcesProperties.getImgPath();
            String realPath = this.getServletContext().getRealPath(imgPath);
            Map<String, String> params = FileUploadUtil.getUploadParam(req, imgPath, realPath);
            req.setAttribute("param", params);
            method = params.get("method");
        }
        Class<?> c = this.getClass();
        Method[] methods = c.getDeclaredMethods();
        for (Method m : methods) {
            if (m.isAnnotationPresent(RequestMethod.class)) {
                RequestMethod annotation = m.getAnnotation(RequestMethod.class);
                if (annotation.method().equals(method)) {
                    try {
                        m.invoke(this, req, resp);
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }
    }
}
